﻿using System;
using System.Runtime.InteropServices;
using UnityEngine;

namespace Recast
{
    public class NavMesh : MonoBehaviour
    {
        IntPtr handle = IntPtr.Zero;
        [SerializeField]
        TextAsset content;

        NavMeshQuery navMeshQuery;

        private void Awake()
        {
            NavMeshInterface.SetupLog();
            navMeshQuery = GetComponent<NavMeshQuery>();
        }

        // Use this for initialization
        void Start()
        {
            handle = NavMeshInterface.LoadNavMesh(content.bytes, content.bytes.Length);

            if(handle != IntPtr.Zero && null != navMeshQuery && navMeshQuery.Valid)
            {
                if(!navMeshQuery.InitNavMeshQuery(handle,2048))
                {
                    Debug.LogError($"InitNavMeshQuery Failed ...");
                    return;
                }

                //ready filter
                var queryFilter = NavMeshInterface.AllocNavMeshQueryFilter();
                float[] areaCosts = new float[]
                {
                    1,1,1,1,2,1.5f
                };
                for(int i = 0; i < areaCosts.Length; ++i)
                {
                    NavMeshInterface.SetAreaCost(queryFilter, i, areaCosts[i]);
                }
                NavMeshInterface.SetIncludeFlags(queryFilter, 65519);
                NavMeshInterface.SetExcludeFlags(queryFilter, 0);

                float[] outList = new float[3];
                uint endRef = 0;
                float[] pos = new float[3]
                {
                    0.2268f,1.24f,10.05f,
                };

                float[] pickExt = new float[3]
                {
                    2,4,2
                };

                uint status = navMeshQuery.FindNearestPoly(pos, pickExt, queryFilter, out endRef,outList);
                if(status.Succeed())
                {
                    UnityEngine.Debug.Log($"FindNearestPoly Succeed [polyref]:{endRef} [pt]:({outList[0]},{outList[1]},{outList[2]})");
                }
                NavMeshInterface.FreeNavMeshQueryFilter(queryFilter);
            }
        }

        private void OnDestroy()
        {
            if (handle != IntPtr.Zero)
            {
                NavMeshInterface.FreeNavMesh(handle);
                handle = IntPtr.Zero;
            }
        }
    }
}